<template>
  <div class="inner-container">
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item label="类别名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入类别名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" style="margin-bottom:8px">
      <el-col :span="1.5">
        <el-button type="primary" plain @click="showAddDialog">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain @click="showEditDialog" :disabled="selectedIds.length!==1">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain @click="handleDelete" :disabled="!selectedIds.length">删除</el-button>
      </el-col>
    </el-row>

    <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50"/>
      <el-table-column prop="id" label="#" align="center" width="50"/>
      <el-table-column prop="name" label="类别名称" align="center"/>
      <el-table-column prop="keywords" label="关键词" align="center" show-overflow-tooltip/>
      <el-table-column prop="sort" label="排序序号" align="center"/>
      <el-table-column prop="enable" label="启用状态" align="center">
        <template #default="scope">
          <el-switch
              v-model="scope.row.enable"
              :active-value="1"
              :inactive-value="0"
              @change="handleEnable(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="isDisplay" label="显示状态" align="center">
        <template #default="scope">
          <el-switch
              v-model="scope.row.isDisplay"
              :active-value="1"
              :inactive-value="0"
              @change="handleDisplay(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="150">
        <template #default="scope">
          <el-link type="primary" :icon="Edit" @click="showEditDialog(scope.row)">修改</el-link>
          <el-link type="primary" :icon="Delete" @click="handleDelete(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <el-pagination
        background
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="closeDialog" append-to-body>
      <el-form ref="dialogFormRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="类别名称" prop="name">
          <el-input v-model="formData.name" placeholder="类别名称"/>
        </el-form-item>
        <el-form-item label="关键词" prop="keywords">
          <el-input v-model="formData.keywords" placeholder="各关键词使用英文的逗号分隔"/>
        </el-form-item>
        <el-form-item label="启用状态" prop="enable">
          <el-radio-group v-model="formData.enable">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示状态" prop="isDisplay">
          <el-radio-group v-model="formData.isDisplay">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="formData.sort" type="number" placeholder="排序序号，0-255之间的整数"/>
        </el-form-item>
      </el-form>
      <template #footer class="dialog-footer">
        <el-button type="primary" @click="saveOrUpdate">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Delete, Edit} from '@element-plus/icons-vue'
import request from '@/utils/request'

// --------------------------------------------------
const loading = ref(false)
const queryFormRef = ref()
const queryParams = ref({pageNum: 1, pageSize: 5})
const total = ref(0)
const tableData = ref([])
const selectedIds = ref([])

const listData = () => {
  loading.value = true
  request.get('/content/category/list', {
    params: queryParams.value
  }).then(res => {
    total.value = res.data.total;
    tableData.value = res.data.list;
    loading.value = false
  })
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const handleQuery = () => {
  queryParams.value.pageNum = 1
  listData()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  listData()
}

const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  listData()
}

const handleDelete = (row) => {
  let ids = row ? [row.id] : [...selectedIds.value]
  if (ids.length === 0) {
    ElMessage.error('请选择要删除的记录')
    return
  }
  ElMessageBox.confirm('确定删除吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.post(`/content/category/delete`, ids)
        .then(res => {
          ElMessage.success('删除成功')
          selectedIds.value.length = 0
          listData()
        })
  })
}

const handleEnable = (row) => {
  let operate = row.enable === 0 ? 'enable' : 'disable'
  request.post(`/content/category/${row.id}/${operate}`)
      .then(res => {
        ElMessage.success('操作成功')
      })
}

const handleDisplay = (row) => {
  let operate = row.isDisplay === 0 ? 'display' : 'hidden'
  request.post(`/content/category/${row.id}/${operate}`)
      .then(res => {
        ElMessage.success('操作成功')
      })
}

// --------------------------------------------------
const dialogTitle = ref('')
const dialogVisible = ref(false)
const dialogFormRef = ref()
const formData = ref({
  id: undefined,
  name: undefined,
  keywords: undefined,
  enable: 1,
  isDisplay: 1,
  sort: undefined
})
const formRules = ref({
  name: [
    {required: true, message: '类别名称不能为空'},
    {min: 1, max: 32, message: '类别名称必须是1-32个字符组成'}
  ],
  sort: [{required: true, message: '排序序号不能为空'}]
})

const showAddDialog = () => {
  dialogTitle.value = '新增类别'
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  let id = row.id || selectedIds.value
  request.get(`/content/category/${id}`)
      .then(res => {
        formData.value = res.data
        dialogTitle.value = '修改类别'
        dialogVisible.value = true
      })
}

const closeDialog = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    keywords: undefined,
    enable: 1,
    isDisplay: 1,
    sort: undefined
  }
  dialogFormRef.value.resetFields()
  dialogVisible.value = false
}

const saveOrUpdate = () => {
  dialogFormRef.value.validate(valid => {
    if (!valid) {
      ElMessage.error('请正确填写参数')
      return false
    }
    console.log(formData.value)
    let operate = formData.value.id ? 'update' : 'add-new'
    request.post(`/content/category/${operate}`, formData.value)
        .then(res => {
          ElMessage.success('保存成功')
          closeDialog()
          listData()
        })
  })
}

// --------------------------------------------------
onMounted(() => {
  listData()
})
</script>

<style scoped>

</style>
